package com.ug_project.spring_dict.DataAccess

import com.ug_project.spring_dict.DataAccess.Migrations.Users
import com.ug_project.spring_dict.Entities.User
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
import java.security.MessageDigest
import java.util.*

class AccountRepository {
    fun insert(user: User) : User{
        val db = connectDb()

        transaction(db) {
            val statement = Users.insert {

//                user.signInPassword = String(MessageDigest.getInstance("MD5").digest(user.signInPassword.toByteArray()))

                it.fillBasicData(user)

                it[name] = user.name
                it[signInName] = user.signInName
                it[signInPassword] = user.signInPassword
                it[integral] = user.integral
                it[permission] = user.permission
            }

            user.id = statement.generatedKey as Int
        }
        return user
    }

    fun createAdminIfNotExists(user: User) : Boolean {
        var retv = true

        transaction(connectDb()) {
            if (Users.selectAll().count() == 0) insert(user)
            else retv = false
        }

        return retv
    }

    fun findByName(name: String) : User?{
        val user = transaction(connectDb()) {
            Users.select { Users.signInName eq name }.firstOrNull()?.run {this.toEntity()}
        }
        return user
    }
    fun getAllUser(): Array<User>{

        val users = transaction {
            Users.selectAll().map { it.toEntity() }
        }
        return users.toTypedArray()
    }

    private fun ResultRow.toEntity() : User{
        val user = User()

        getBasicData(Users, user)

        user.name = this[Users.name]
        user.signInName = this[Users.signInName]
        user.signInPassword = this[Users.signInPassword]
        user.integral = this[Users.integral]
        user.permission = this[Users.permission]

        return user
    }
}